package com.eliza.library.permission

import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import androidx.activity.ComponentActivity
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity

object PermissionUtils {
    lateinit var registerForActivityResult: ActivityResultLauncher<String>

    var requestComponentActLauncher =
            fun(activity: ComponentActivity, callback: ActivityResultCallback<Boolean>): ActivityResultLauncher<String> {
                return activity.registerForActivityResult(
                        ActivityResultContracts.RequestPermission(),
                        callback
                )
            }
    fun requestPermissions(activity: Activity, requestCode: Int, vararg requestedPermission: String) {
        ActivityCompat.requestPermissions(activity, requestedPermission, requestCode)
    }

    fun showPermissionRationale(activity: Activity, requestedPermission: String, handle: () -> Unit) {
        //解釋權限
        ActivityCompat.shouldShowRequestPermissionRationale(
                activity, requestedPermission
        ).let {
            if (it) {
                handle()
            }
        }
    }

    fun hasPermission(context: Context, requestedPermission: String) =
            ContextCompat.checkSelfPermission(
                    context,
                    requestedPermission
            ) == PackageManager.PERMISSION_GRANTED

}